<template>
  <div>
    <Category :scene="scene" />
    <el-card style="margin: 10px 10px;">
      <div v-show="categoryStore.category3Id && scene === 0">
        <el-button type="primary" size="default" icon="Plus" :disabled="categoryStore.category3Id ? false : true"
          @click="addAttrPlatform">添加平台属性</el-button>
        <el-table :border="true" style="margin: 10px 10px;" :data="attrValueList">
          <el-table-column label="序号" width="80px" type="index" align="center" />
          <el-table-column label="属性名称" width="120" prop="attrName" align="center" />
          <el-table-column label="属性值名称" prop="attrValueItemList" align="center">
            <template #="{ row, $index, }">
              <el-tag v-for="(item, index)
                in row.attrValueItemList" :key="index" size="small" type="info">
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #="{ row, $index, }">
              <el-button type="primary" size="mini" icon="Edit" @click="handleEdit(row)" />
              <!-- 删除功能增加一个pop组件 以便二次确认 -->
              <el-popconfirm :title="`确认删除${row.attrName}吗?`" icon="Delete" @confirm="handleDelete(row)" width="200px">
                <template #reference>
                  <el-button type="danger" size="mini" icon="Delete" />
                </template>
              </el-popconfirm>


            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
  <div v-show="scene == 1">
    <!-- 展示 添加属性与修改数据的结构 -->
    <el-form ref="formRef" :inline="true">
      <el-form-item label="属性名称">
        <el-input placeholder="请输入属性名称" v-model="attrParam.attrName" />
      </el-form-item>
    </el-form>
    <el-button :disabled="!attrParam.attrName" type="primary" icon="Plus" size="default"
      @click="addAttrValue">添加属性值</el-button>
    <el-button type="primary" size="default" @click="cancel">取消</el-button>
    <el-table border style="margin:10px 0px" :data="attrParam.attrValueItemList">
      <el-table-column type="index" label="序号" width="180" align="center" />
      <el-table-column label="属性值名称" width="180">
        <!-- row：当前这一行的数据 -->
        <template #="{ row, $index, }">
          <el-input :ref="(vc: any) => inputArr[$index] = vc" v-if="row.flag" @blur="toLook(row, $index)"
            v-model="row.valueName" placeholder="请输入属性值名称" />
          <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="属性值操作">
        <template #="{ row, $index, }">
          <el-button type="danger" size="mini" icon="Delete" @click="deleteAttrValue(row, $index)" />
        </template>
      </el-table-column>
    </el-table>
    <el-button :disabled="attrParam.attrValueItemList.length > 0 ? false : true" type="primary" icon="Plus"
      size="default" @click="save">保存</el-button>
    <el-button type="primary" size="default" @click="cancel">取消</el-button>
  </div>
</template>

<script setup lang="ts">
import Category from '@/components/Category/index.vue';
// 引入属性分类的小仓库
import { useCategoryStore } from '@/store/modules/category';
import { reactive, watch, nextTick, onBeforeUnmount } from 'vue';
import { addOrUpdateAttr, getAttrInfoList, deleteAttr } from '@/api/product/attr';
import type { Response } from '@/api/type';
import type { AttrValueItem, AttrValueList, AttrValueVO } from '@/api/product/attr/type';
import { ElMessage } from 'element-plus';
import { ref } from 'vue';


//  引入属性分类的小仓库
let categoryStore = useCategoryStore()

//  定义 列表的属性值
let attrValueList = ref<AttrValueList>([])

// 添加属性值
const addAttrPlatform = () => {
  // 添加属性之前，先清空之前的数据
  Object.assign(attrParam, {
    attrName: '',
    attrValueItemList: [],
    categoryId: categoryStore.category3Id as number,
    categoryLevel: 3
  })
  // 切换为添加或者编辑属性值的状态
  scene.value = 1;

}
// 编辑属性值
// 这里的row是el-table传入的参数

const addAttrValue = () => {
  //  清空之前的数据
  //  添加一个一个空的属性-进行站位
  attrParam.attrValueItemList.push({
    valueName: '',
    flag: true
  })
  // 获取最后el-input组件聚焦
  nextTick(() => {
    //  获取最后一个el-input组件聚焦
    inputArr.value[inputArr.value.length - 1].focus();
  })
}
const handleEdit = (row: AttrValueVO) => {
  scene.value = 1;
  console.log(row);
  // 实现编辑属性的深copy
  Object.assign(attrParam, JSON.parse(JSON.stringify(row)))
}
const handleDelete = async (row: AttrValueItem) => {
  console.log(row.id);
  let result = await deleteAttr(row.id as number);
  if (result.code === 200) {
    ElMessage.success('删除成功');
    getCA();
  } else {
    ElMessage.error(result.message);
  }

}

// 定义card组件内容切换变量
let scene = ref<number>(0); // scene 0:展示 1: 编辑属性, 添加属性
// 定义一个响应式数据，控制编辑模式与查看模式的切换



// 收集新增的属性的数据
let attrParam = reactive<AttrValueVO>({
  attrName: '',
  attrValueItemList: [
    {
      valueName: ''
    }
  ],
  categoryId: categoryStore.category3Id as number,
  categoryLevel: 3
})

//  准备一个数组：将来存储对应的组件实例 el-put
let inputArr = ref<any[]>([])

const cancel = () => {
  scene.value = 0;
  getCA();
}
const save = async () => {
  console.log(attrParam);
  let result: Response<void> = await addOrUpdateAttr(attrParam);
  console.log('save:', result);
  if (result.code === 200) {
    // 切换场景
    scene.value = 0;
    ElMessage.success(attrParam.id ? '修改成功' : '添加成功');
    getCA();
  } else {
    ElMessage.error(result.message);
  }
}

// 建通 三级分类ID的变化
watch(() => categoryStore.category3Id, () => {
  if (!categoryStore.category3Id) {
    attrValueList.value = [];
    return;
  }
  getCA();
})

const getCA = async () => {
  let { category1Id, category2Id, category3Id } = categoryStore;
  //  获取属性列表
  let result: Response<AttrValueList> = await getAttrInfoList(category1Id as number, category2Id as number, category3Id as number);
  console.log('getCA:', result);
  if (result.code === 200) {
    // console.log(result.data);
    attrValueList.value = result.data || [];
  } else {
    ElMessage.error(result.message);
  }
}

const deleteAttrValue = async (row: AttrValueItem, index: number) => {
  let existedValue: AttrValueItem | undefined = attrParam.attrValueItemList.find(item => {
    return item.valueName === row.valueName
  });
  if (existedValue) {
    attrParam.attrValueItemList.splice(index, 1);
  }
  //  调用接口
  // let result: Response<void> = await deleteAttrValueById(id);
  // console.log('result:', result);
  // if (result.code === 200) {
  //   //  提示信息
  //   ElMessage.success('删除成功');
  //   //  删除成功之后，重新获取数据
  //   await getCA();
  // }
}

// 属性值表单元素时区焦点事件回调
const toLook = (row: AttrValueItem, index: number) => {
  if (row.valueName.trim() == '') {
    // 删除掉对应属性值为空的元素
    attrParam.attrValueItemList.splice(index, 1);
    ElMessage.error('请输入属性值名称');
    return;
  }
  let repeat: AttrValueItem | undefined = attrParam.attrValueItemList.find(item => {
    // 切记把当前失去焦点的属性值对象删除掉
    if (item != row) {
      return item.valueName === row.valueName
    }
  });
  if (repeat) {
    // 将重复的属性值从数组当中删除掉
    attrParam.attrValueItemList.splice(index, 1);
    ElMessage.error('属性值名称不能重复');
    return;
  }

  //  切换为编辑模式
  row.flag = false;
}
const toEdit = (row: AttrValueItem, index: number) => {
  //  切换为编辑模式
  row.flag = true;
  // nextTick:响应式数据发生变化，获取更新的dom
  nextTick(() => {
    //  让当前的input获取焦点
    inputArr.value[index].focus();
  })

}


onBeforeUnmount(() => {
  //  组件销毁之前，将属性值列表清空
  attrValueList.value = [];
  // 将属性仓库清空
  categoryStore.$reset();

})


</script>

<style scoped lang="scss"></style>